#!/bin/bash
###
 # @Author: didiplus
 # @Description: 内核参数安全优化脚本 - 等保2.0
 # @Date: 2025-06-19 23:28:16
 # @LastEditors: didiplus
 # @LastEditTime: 2025-06-19 23:32:17
 # @FilePath: /script/SecGuardian/modules/secure_sysctl.sh
 # @Version: 1.0
### 

secure_sysctl() {
SYSCTL_CONF="/etc/sysctl.conf"
BACKUP_FILE="/etc/sysctl.conf.bak.$(date +%F_%T)"

echo "🔒 正在备份原始内核配置文件到：$BACKUP_FILE"
cp -a "$SYSCTL_CONF" "$BACKUP_FILE"

declare -A sysctl_kv=(
    [net.ipv4.ip_forward]=0
    [net.ipv4.conf.all.send_redirects]=0
    [net.ipv4.conf.default.send_redirects]=0
    [net.ipv4.conf.all.accept_redirects]=0
    [net.ipv4.conf.default.accept_redirects]=0
    [net.ipv4.conf.all.accept_source_route]=0
    [net.ipv4.conf.default.accept_source_route]=0
    [net.ipv4.conf.all.rp_filter]=1
    [net.ipv4.conf.default.rp_filter]=1
    [net.ipv4.tcp_syncookies]=1
    [net.ipv4.icmp_echo_ignore_broadcasts]=1
    [net.ipv4.icmp_ignore_bogus_error_responses]=1
    [kernel.randomize_va_space]=2
    [kernel.sysrq]=0
    [kernel.core_uses_pid]=1
    [fs.suid_dumpable]=0
    [kernel.printk]="4 4 1 7"
)

echo "🚀 开始应用内核参数优化..."

for key in "${!sysctl_kv[@]}"; do
    value="${sysctl_kv[$key]}"
    if grep -q "^$key" "$SYSCTL_CONF"; then
        sed -i "s|^$key.*|$key = $value|" "$SYSCTL_CONF"
        echo "✔️ 更新：$key = $value"
    else
        echo "$key = $value" >> "$SYSCTL_CONF"
        echo "➕ 添加：$key = $value"
    fi
done

# 立即生效
sysctl -p "$SYSCTL_CONF" &>/dev/null && echo "✅ 内核参数已加载生效"

# 校验结果
echo -e "\n📋 当前关键内核参数状态（部分）："
for key in "${!sysctl_kv[@]}"; do
    sysctl "$key"
done
}


